package com.example.demo.config.session;

import com.example.demo.config.globalexception.SystemRuntimeException;
import com.example.demo.model.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author
 * 登录校验拦截器
 */
@Component
@Slf4j
public class AuthorizationInterceptor implements HandlerInterceptor {

    /**
     * 用户ID
     */
    public static final String USER_KEY = "USER_ID";
    /**
     * 用户信息
     */
    public static final String USER_INFO = "USER_INFO";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        PassToken annotation;
        if(handler instanceof HandlerMethod) {
            annotation = ((HandlerMethod) handler).getMethodAnnotation(PassToken.class);
            // 如果加上了passToken注解则不需要校验token
            if (annotation!=null && annotation.validate()){
                log.info("不需要token验证");
                return true;
            }
        }else{
            return true;
        }

        // 从header中获取token
        String token = request.getHeader("token");
        if(token == null){
            log.info("缺少token，拒绝访问");
            throw new SystemRuntimeException("缺少token，拒绝访问");
        }

        // 查询token信息
//        User user = redisUtils.get(USER_INFO+token,User.class);
//        if(user == null){
//            log.info("token不正确，拒绝访问");
//            return false;
//        }

        // token校验通过，将用户信息放在request中，供需要用user信息的接口里从token取数据
        request.setAttribute(USER_KEY, "123456");
        request.setAttribute(USER_INFO, simulatorUser());

        return true;
    }

    /**
     * 模拟用户
     *
     * @return 模拟用户
     */
    private static User simulatorUser(){
        User user = new User();
        user.setId("123456");
        user.setUserName("topCombine");
        return user;
    }

}
